<template>
  <div class="addTask-page">
    <FixedOperation>
      <div class="my-header">
        <h4 class="flex-header-7">
          <svg-icon
            :icon-class="'svg_tbfk'"
            class="w-30px h-30px align-middle"
            style="margin-right: 10px; margin-top: -2px"
          />
          <span>{{ titleName }}</span>
        </h4>
        <div class="flex-header-5">
          <span style="width: 88px"></span>
          <el-button
            @click="importList"
            type="primary"
            text
            v-if="formParams.businessType == 13 && isAdd"
          >
            批量导入
          </el-button>

          <el-button
            type="primary"
            round
            icon="Select"
            @click="handleSubmit"
            :loading="btnLoading"
          >
            提交
          </el-button>

          <el-button round @click="handleBack" type="primary" plain
            >返回</el-button
          >
        </div>
      </div>
    </FixedOperation>
    <div class="addTask-com">
      <el-form
        ref="ruleFormRef"
        :model="formParams"
        :rules="formRules"
        label-position="right"
        label-width="120"
      >
        <div>
          <TitleName
            title="任务基本信息"
            icon="i-carbon-bookmark-filled"
            class="title text-#000 ml-20px"
          ></TitleName>

          <el-row :gutter="grid" class="px-20" style="margin-top: 24px">
            <el-col :span="12">
              <el-form-item label="任务标题:" prop="title">
                <el-input
                  v-model.trim="formParams.title"
                  placeholder="请输入任务标题"
                ></el-input>

                <!-- :disabled="isDisabled" -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务编码:">
                <el-input
                  placeholder="系统自动生成任务编码"
                  disabled
                  v-model.trim="formParams.taskNo"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务类型:" prop="businessType">
                <el-tree-select
                  v-model="formParams.businessType"
                  @change="changeType"
                  placeholder="请选择业务分类"
                  :data="businessOptions"
                  default-expand-all
                  style="width: 100%"
                  :disabled="isDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="任务级别:" prop="impSign">
                <el-radio-group
                  v-model="formParams.impSign"
                  @change="radioClick($event)"
                  :disabled="isDisabled"
                >
                  <template
                    v-for="(item, index) in work_order_level"
                    :key="index"
                  >
                    <el-radio :label="item.value" :value="item.value">{{
                      item.label
                    }}</el-radio>
                  </template>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发 起 人:" prop="">
                <div>{{ initiator }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isBusinessName">
              <el-form-item :label="associatedTitle" prop="businessId">
                <el-select
                  v-model.trim="formParams.businessId"
                  placeholder="请选择"
                  filterable
                  remote
                  :remote-method="queryProject"
                  @change="changeBusinessId"
                  clearable
                  style="width: 100%"
                  :disabled="isDisabled"
                >
                  <el-option
                    v-for="item in optionsProjectName"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isBusinessType">
              <el-form-item label="电话服务单:" prop="businessName">
                <el-input
                  v-model="formParams.businessName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" class="font-15">
              <el-form-item label="任务到期提醒:" prop="">
                <el-select v-model="formParams.warning" :disabled="isDisabled">
                  <el-option
                    v-for="(item, index) in reminder_opening"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <TitleName
            :title="`任务详细信息(${businessTitle})`"
            icon="i-carbon-bookmark-filled"
            class="title"
            style="margin-top: 30px; margin-bottom: 24px"
          ></TitleName>
          <el-row
            :gutter="grid"
            class="px-20"
            v-if="businessTitle == '上门服务'"
          >
            <el-col :span="12">
              <el-form-item label="客户名称:" prop="customerId">
                <el-select
                  v-model="formParams.customerId"
                  placeholder="请选择客户名称"
                  @focus="selectCustomerFn('customerId')"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in customerOption['customerId']"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人/电话:" prop="contactTel">
                <el-input
                  v-model.trim="formParams.contactTel"
                  placeholder="请输入任务标题"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上门地址:" prop="goAddr">
                <el-input
                  v-model.trim="formParams.goAddr"
                  placeholder="请输入任务标题"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户地址:" prop="cusAddr">
                <el-input
                  v-model.trim="formParams.cusAddr"
                  placeholder="请输入任务标题"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="指派给:" prop="directorId">
                <el-select
                  clearable
                  v-model="formParams.directorId"
                  placeholder="请选择负责人员"
                  @focus="userInputFocus"
                  class="w-full"
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['directorId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计上门时间:" prop="visitTime">
                <el-date-picker
                  v-model="formParams.visitTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="grid"
            class="px-20"
            v-if="businessTitle == '测试问题' || businessTitle == '生产BUG'"
          >
            <el-col :span="12">
              <el-form-item label="严重程度:" prop="severity">
                <el-select
                  v-model="formParams.severity"
                  placeholder="操作状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in task_severity"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="问题分类:" prop="questionType">
                <el-select
                  v-model="formParams.questionType"
                  placeholder="操作状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in task_question_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row
            :gutter="grid"
            class="px-20"
            v-if="businessTitle == '生产BUG'"
          >
            <el-col :span="12">
              <el-form-item label="影响范围:" prop="reach">
                <el-select
                  v-model="formParams.reach"
                  placeholder="影响范围"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in task_reach"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="期望解决时间:"
                prop="endTime"
                :rules="[
                  {
                    required: true,
                    message: '请输入期望完成时间',
                    triggle: 'blur'
                  }
                ]"
              >
                <el-date-picker
                  v-model="formParams.endTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                  @change="timeChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="grid" class="px-20">
            <el-col :span="12" v-if="showProjectName">
              <el-form-item
                label="系统/项目名称:"
                prop="businessName"
                :rules="[
                  {
                    required: true,
                    message: '请选择系统/项目名称',
                    triggle: 'blur'
                  }
                ]"
              >
                <el-autocomplete
                  v-model="name"
                  :fetch-suggestions="querySearch"
                  style="width: 100%"
                  placeholder="系统/项目名称"
                  @select="valueChange"
                  @change="valueChange"
                  @blur="blurValue"
                />
                <!-- <el-select
                  v-model="formParams.businessName"
                  placeholder="系统/项目名称"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in system_or_project_name"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isOperateParentId">
              <el-form-item label="父任务:" prop="parentId">
                <el-select
                  v-model="formParams.parentId"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="父任务"
                  remote-show-suffix
                  :remote-method="remoteMethod"
                  ref="parentInput"
                  style="width: 100%"
                  @focus="parentInputfocus"
                >
                  <!-- <el-option
                    v-if="options.length === 0"
                    label="暂无数据"
                  ></el-option> -->
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                  />
                </el-select>
                <!-- <el-autocomplete
                  v-model="parentId"
                  :fetch-suggestions="querySearchAsync"
                  placeholder="父任务"
                  @select="handleSelect"
                  @change="handleSelect"
                  style="width: 100%"
                  v-if="name"
                />
                <el-input
                  v-else
                  ref="parentInput"
                  placeholder="父任务"

                ></el-input> -->
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-if="businessTitle === '功能需求' || businessTitle === '版本'"
            >
              <el-form-item
                label="期望完成时间:"
                prop="endTime"
                :rules="[
                  {
                    required: true,
                    message: '请输入期望完成时间',
                    triggle: 'blur'
                  }
                ]"
              >
                <el-date-picker
                  v-model="formParams.endTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                  @change="timeChange"
                />
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-if="businessTitle === '功能需求' || businessTitle === '版本'"
            >
              <el-form-item label="开始时间:" prop="startTime">
                <el-date-picker
                  v-model="formParams.startTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-if="businessTitle === '功能需求' || businessTitle === '版本'"
            >
              <el-form-item label="预估工时:" prop="preWorkHour">
                <el-input
                  v-model.trim="formParams.preWorkHour"
                  placeholder="请输入预估工时"
                >
                  <template #append>小时</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-if="businessTitle == '数据统计' || businessTitle == '美工设计'"
            >
              <el-form-item
                label="期望完成时间:"
                prop="endTime"
                :rules="[
                  {
                    required: true,
                    message: '请输入期望完成时间',
                    triggle: 'blur'
                  }
                ]"
              >
                <el-date-picker
                  v-model="formParams.endTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                  @change="timeChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row
            :gutter="grid"
            class="px-20"

          > -->
          <!-- <el-col :span="12">
              <el-form-item label="重要程度" prop="impSign">
                <el-select
                  v-model="formParams.impSign"
                  placeholder="重要程度"
                  clearable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in sys_imp_sign"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          <!-- </el-row> -->

          <el-row :gutter="grid" class="px-20">
            <el-col :span="24">
              <el-form-item :label="taskDescription" prop="remark">
                <editor
                  class="w-full"
                  v-model="formParams.remark"
                  :min-height="192"
                  ref="editor"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="grid" class="px-20">
            <el-col :span="24">
              <el-form-item label="上传附件:">
                <el-upload
                  v-model:file-list="formParams.fileList"
                  class="upload-demo"
                  action="#"
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleFileChange"
                  accept=".rar, .zip, .doc, .docx, .pdf"
                  :show-file-list="false"
                  style="margin-right: 6px"
                >
                  <el-button type="default" style="font-size: 14px"
                    ><el-icon> <UploadFilled /> </el-icon>上传文件</el-button
                  >
                  <template #tip>
                    <div
                      class="el-upload__tip float-right"
                      style="margin-top: 0px"
                    >
                      支持格式:.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                    </div>
                  </template>
                </el-upload>
                <div class="text-14px mt-10px" style="width: 100%">
                  <div v-for="(item, index) in fileList" :key="item.fileId">
                    <a :href="item.url" target="_blank" class="text-#409eff">{{
                      item.origFileName
                    }}</a>
                    <el-button text plain @click="delFileName(index)"
                      >删除</el-button
                    >
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="grid" class="px-20">
            <el-col :span="12" v-if="isSite">
              <el-form-item label="开始时间:" prop="startTime">
                <el-date-picker
                  v-model="formParams.startTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="isSite">
              <el-form-item
                label="期望完成时间:"
                prop="endTime"
                :rules="[
                  {
                    required: true,
                    message: '请输入期望完成时间',
                    triggle: 'blur'
                  }
                ]"
              >
                <el-date-picker
                  v-model="formParams.endTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择时间"
                  style="width: 100%"
                  @change="timeChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="grid" class="px-20">
            <el-col :span="12">
              <el-form-item label="负责人员:" prop="directorId">
                <el-select
                  clearable
                  :disabled="isDisabled"
                  v-model="formParams.directorId"
                  placeholder="请选择负责人员"
                  @focus="userInputFocus"
                  class="w-full"
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['directorId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参与人员:">
                <el-select
                  clearable
                  :disabled="isDisabled"
                  v-model="formParams.playersId"
                  placeholder="请选则参与人员"
                  @focus="participateIdFocus"
                  class="w-full"
                  multiple
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['playersId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通知人员">
                <el-select
                  clearable
                  v-model="formParams.copyId"
                  placeholder="请选择通知人员"
                  @focus="noticeFocus"
                  class="w-full"
                  multiple
                >
                  <el-option
                    v-for="(item, index) in selectOptionObj['copyId']"
                    :key="index"
                    :label="item.label"
                    :value="item.uuid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <!-- 客户弹出框下拉框 -->
    <SelectCustomer
      v-if="dialogParamA.isDialog"
      :dialog-param="dialogParamA"
      @ok="selectCustomerData"
      @close="
        val => {
          dialogParamA.isDialog = false
        }
      "
    ></SelectCustomer>
    <!-- 选择人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectDialogData"
      @close="closeFn"
    ></SelectDialog>
    <!-- 批量导入 -->
    <el-dialog
      title="批量导入"
      v-model="showUpload"
      append-to-body
      @close="closeUpload"
    >
      <el-upload
        ref="uploadRef"
        class="w-full"
        :show-file-list="true"
        @change="fileChange"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :limit="1"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="downloadTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div>
          <el-button type="primary" @click="uploadFiles">确定</el-button>
          <el-button @click="cancelupload">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="AddTasking">
import { isArray } from 'min-dash'
import { reactive, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import useTagsViewStore from '@/store/modules/tagsView'
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import { addManage } from '@/api/system/notice'
import { formRules } from '../modules/formData'
import {
  addTaskList,
  getTaskDetail,
  updateTadk,
  getOrdpurchaseorder,
  getOrdinnerorder,
  getTaskList,
  getProjectNodeList,
  importtemplate,
  importTask
} from '@/api/taskManage/task'
import { getOrdprojectNoPriv } from '@/api/projectManage/project' //项目模糊搜索
import { getOrderList } from '@/api/salesManage/contractManage' //订单模糊搜索
import { getListByCustomerName } from '@/api/customerManage/customerList' //企业客户模糊搜索
import { getBusinessOpportunityListSelect } from '@/api/salesManage/businessManage' //商机模糊搜索
// import { getDetailTactlistByCactName } from '@/api/customerManage/customerList' //联系人模糊搜索

import {
  getCustomerEditInfo,
  getDetailTactlistByCactName
} from '@/api/customerManage/customerList' //客户详情
import { uploadFile, delFile } from '@/api/salesManage/contractManage' //上传文件删除文件
import { format } from 'date-fns'

const { proxy } = getCurrentInstance()

const grid = ref(4)
// 通用数据store
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()

const data = reactive({
  formParams: {
    title: null,
    startTime: null,
    endTime: null,
    impSign: '1',
    directorId: null, //负责人
    playersId: null, //参与人员
    serviceType: null, //任务提醒
    reminderMethod: '0', //提醒方式
    remark: '',
    businessType: null,
    businessName: null,
    businessId: null,
    filePath: [],
    fileName: [], //文件名
    customerId: '', //客户id
    customerName: '', //客户名称
    customerType: 'customer', //客户选择下拉
    severity: '',
    questionType: '',
    fqr: '',
    fqdw: '',
    warning: '2'
  },
  dialogParamA: {}, //客户弹窗
  customerOption: {}, //客户选择下拉
  isSite: false,
  isBusinessName: false,
  associatedTitle: '',
  titleName: '新建任务', //标题名称
  selectOptionObj: {}, // 参与人员
  dialogParam: {},
  optionsProjectName: [], //关联项目
  optionsOrder: [] //关联订单
})
const {
  formParams,
  selectOptionObj,
  dialogParam,
  rulesForm,
  optionsProjectName,
  isBusinessName,
  associatedTitle,
  titleName,
  isSite,
  dialogParamA,
  customerOption
} = toRefs(data)
const {
  task_reminder_time, //任务提醒
  rsgl_urgent_status, //紧要程度
  sys_imp_sign, //重要程度
  task_severity, //严重程度
  system_or_project_name, //系统/项目名称
  task_question_type, //问题分类
  rsgl_question_type, //问题类型
  task_order_type, //任务类型
  work_order_level, //任务级别
  task_reach, //影响范围
  reminder_opening
} = proxy.useDict(
  'task_reminder_time',
  'rsgl_urgent_status',
  'sys_imp_sign',
  'task_severity',
  'system_or_project_name',
  'task_question_type',
  'rsgl_question_type',
  'task_order_type',
  'work_order_level',
  'task_reach',
  'reminder_opening'
)
const businessTitle = ref('普通工单')
const taskDescription = ref('任务描述')
const isBusinessType = ref(false)
const playersId = ref([])
const isDisabled = ref(false)
const btnLoading = ref(false) //按钮加载状态
//当前时间
const gettime = ref('')
/*** 文件上传 start */
let fileList = ref([])
// 发起人
let initiator = ref('')
const props = defineProps({
  // 弹出框是否显示
  // dialogParam: {
  //   required: true
  // }
})
const name = ref()
watch(
  [() => route.query.id, () => route.query.taskParam],
  async val => {
    if (route.query.id && !!location.href.match(/editTasking/)) {
      titleName.value = '编辑任务'
      getBusinessDetail() //查询详情接口
    } else if (
      JSON.stringify(route.query.taskParam) != '{}' &&
      JSON.stringify(route.query.taskParam)
    ) {
      let taskParamData =
        route.query.taskParam && JSON.parse(route.query.taskParam)
      if (taskParamData && taskParamData.businessId) {
        formParams.value.businessId = taskParamData.businessId
        formParams.value.remark = taskParamData.remark
        formParams.value.businessName = taskParamData.businessName
        formParams.value.businessType = taskParamData.businessType
      } else if (
        taskParamData &&
        (taskParamData.businessType == '3' || taskParamData.businessType == '5')
      ) {
        formParams.value.businessType = taskParamData.businessType
      }
      isBusinessName.value = true
      isSite.value = true
      taskDescription.value = '任务描述'
      formParams.value.remark = formParams.value.remark
        ? formParams.value.remark
        : ''
      queryProject(formParams.value.businessName)
      //   changeType(taskParamData.businessType)

      init()
    } else {
      titleName.value = '新建任务'
    }
  },
  {
    immediate: true
  }
)

// 工单转任务
const workOrderForm = ref({})
watch(
  () => route.query.workOrderTransform,
  val => {
    if (val) {
      workOrderForm.value = JSON.parse(sessionStorage.getItem('workOrderForm'))
      fileList.value = workOrderForm.value.fileList
      formParams.value.impSign = workOrderForm.value.level
      formParams.value.title = workOrderForm.value.theme
      formParams.value.remark = workOrderForm.value.details
    }
  },
  { immediate: true }
)
//初始化
const isAdd = ref(true)
async function init() {
  isAdd.value = !!location.href.match(/addTasking/)
  initiator.value =
    userStore.user.params.orgName +
    '-' +
    userStore.user.dept.deptName +
    '-' +
    userStore.user.nickName
  // +
  // '-' +
  // userStore.user.phonenumber
  getTime()
}
init()
//获取详情
async function getBusinessDetail() {
  if (route.query.id) {
    await getTaskDetail({ id: route.query.id }).then(res => {
      formParams.value = res.data
      playersId.value = res.data.playersId
      let newArr = []
      let filePathList = res.data.filePath ? res.data.filePath.split(',') : ''
      let fileNameList = res.data.fileName ? res.data.fileName.split(',') : ''
      if (res.data.filePath) {
        filePathList.map(item => {
          newArr.push({
            url: item,
            fileId: '',
            origFileName: '',
            fileName: item
              .substring(item.lastIndexOf('attach/'))
              .replace('attach/', '')
          })
        })
        fileNameList.map((item, i) => {
          if (newArr[i]) {
            newArr[i].origFileName = item
          }
        })
        fileList.value = newArr
      }
      formParams.value.playersId = res.data.players
        ? res.data.players.split(',')
        : ''

      formParams.value.copyId = res.data.copyId
        ? res.data.copyId.split(',')
        : ''

      isDisabled.value = true
      name.value = formParams.value.businessName
      if (formParams.value.parentId && formParams.value.parentIdCn) {
        options.value = [
          {
            title: formParams.value.parentIdCn,
            id: formParams.value.parentId
          }
        ]
      }

      customerOption.value['customerId'] = [
        {
          id: formParams.value.customerId,
          label: formParams.value.customerName
        }
      ]

      queryProject(formParams.value.businessName)
      changeType(formParams.value.businessType, false)
      getDefaultUserInfo(formParams.value.directorId)
      // 回显通知人员
      if (formParams.value.copyId) {
        const copyIdArr = Array.isArray(formParams.value.copyId)
          ? formParams.value.copyId
          : formParams.value.copyId.split(',')
        const copyName = formParams.value.copyName.split(',')
        selectOptionObj.value.copyId = copyIdArr.map((item, index) => {
          return {
            label: copyName[index],
            uuid: copyIdArr[index]
          }
        })
      }
    })
  }
}
//关联项目类型
function changeBusinessId(val) {
  formParams.value.businessName = optionsProjectName.value.find(
    item => item.value == val
  )
    ? optionsProjectName.value.find(item => item.value == val).label
    : '--'
}
//关联项目名称
async function queryProject(val) {
  optionsProjectName.value = []
  switch (formParams.value.businessType) {
    case '1': //项目
      associatedTitle.value = '关联项目:'
      const proList = await getOrdprojectNoPriv({
        proName: val,
        pageSize: 20
      })

      if (proList.code === 200) {
        optionsProjectName.value = (proList.rows || []).map(v => ({
          label: v.proName,
          value: v.projectId
        }))
      }
      break
    case '2':
      associatedTitle.value = '关联订单:'
      const orderList = await getOrderList({
        title: val,
        pageSize: 20
      })

      if (orderList.code === 200) {
        optionsProjectName.value = (orderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '3': //客户
      associatedTitle.value = '关联客户:'
      const customerList = await getListByCustomerName({
        customer: val,
        pageSize: 20
      })

      if (customerList.code === 200) {
        optionsProjectName.value = (customerList.data || []).map(v => ({
          label: v.customerName,
          value: v.id
        }))
      }
      break
    case '4': //商机
      associatedTitle.value = '关联商机:'
      optionsProjectName.value = []
      const businessList = await getBusinessOpportunityListSelect({
        keyword: val,
        pageSize: 100,
        pageNum: 1
      })

      if (businessList.code === 200) {
        optionsProjectName.value = (businessList.rows || []).map(v => ({
          label: v.titleName,
          value: v.id
        }))
      }

      break
    case '5': //联系人
      associatedTitle.value = '关联联系人:'
      optionsProjectName.value = []
      const contactsNameList = await getDetailTactlistByCactName({
        pageSize: 20,
        entId: '',
        contactName: val
      })

      if (contactsNameList.code === 200) {
        optionsProjectName.value = (contactsNameList.data || []).map(v => ({
          label: v.contactName,
          value: v.id
        }))
      }
      break
    case '6': //采购订单
      optionsProjectName.value = []
      associatedTitle.value = '关联采购订单:'
      const ordpurchaseorderList = await getOrdpurchaseorder({
        title: val,
        pageSize: 20
      })
      if (ordpurchaseorderList.code === 200) {
        optionsProjectName.value = (ordpurchaseorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
    case '7': //内部订单
      associatedTitle.value = '关联内部订单:'
      optionsProjectName.value = []
      const ordinonerorderList = await getOrdinnerorder({
        title: val,
        pageSize: 20
      })

      if (ordinonerorderList.code === 200) {
        optionsProjectName.value = (ordinonerorderList.rows || []).map(v => ({
          label: v.title,
          value: v.id
        }))
      }
      break
  }
}

/**** 归属人员 模块 start */
/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId) {
  let id = ''
  if (userId) {
    id = userId
  }
  //获取人员数据
  const deptUserData = await commonStore.getUseTreeData({ deptId: 100 })
  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, id, 'id', [])
  selectOptionObj.value.directorId = obj
  formParams.value.directorId = obj && obj.length > 0 ? obj[0].uuid : ''
}

//任务类型
const businessOptions = computed(() => arrayToTree(ref(task_order_type).value)) // 工单类型树结构
// 判断是否显示--系统/项目名称:
const devType = computed(() => {
  return businessOptions.value
    .filter(v => v.label.includes('研发'))[0]
    ?.children.map(v => v.label)
})
const showProjectName = computed(() => {
  return devType.value?.find(v => v === businessTitle.value)
})

const isOperateParentId = ref(false)
function changeType(val, clear = true) {
  optionsProjectName.value = [] // 切换关联数据
  proxy.$nextTick(() => {
    if (devType.value.indexOf(businessTitle.value) < 0 && clear) {
      formParams.value.businessName = ''
      name.value = ''
    }
  })

  const findVal = ref(task_order_type).value.find(v => v.value === val)
  // 隐藏电话服务单
  isBusinessType.value = false
  isOperateParentId.value = false
  // 新增任务改变任务类型时，清除formParams  删除详细信息，关联信息/电话服务单
  const form = { ...formParams.value }
  if (!location.href.includes('editTasking')) {
    formParams.value = {
      title: form.title,
      startTime: null,
      endTime: null,
      impSign: form.impSign,
      directorId: null, //负责人
      playersId: null, //参与人员
      serviceType: null, //任务提醒
      reminderMethod: '0', //提醒方式
      remark:
        workOrderForm.value && workOrderForm.value.details
          ? workOrderForm.value.details
          : formParams.value.remark,
      businessType: form.businessType,
      businessName: form.businessName,
      businessId: null,
      filePath: [],
      fileName: [], //文件名
      customerId: '', //客户id
      customerName: '', //客户名称
      customerType: 'customer', //客户选择下拉
      severity: '',
      questionType: '',
      warning: '2'
    }
  }
  businessTitle.value = findVal.label
  if (businessTitle.value == '客户跟进') {
    isBusinessName.value = true
    isSite.value = true
    taskDescription.value = '任务描述'
    associatedTitle.value = '关联客户:'
    // 工单转任务
    if (workOrderForm.value.customerId) {
      optionsProjectName.value = [
        {
          value: workOrderForm.value.customerId,
          label: workOrderForm.value.customerIdCn
        }
      ]
      formParams.value.businessId = workOrderForm.value.customerId
    }
  } else if (businessTitle.value == '订单跟进') {
    isBusinessName.value = true
    isSite.value = true
    taskDescription.value = '任务描述'
    associatedTitle.value = '关联订单:'
    // 工单转任务
    if (workOrderForm.value.linkOrder) {
      optionsProjectName.value = [
        {
          value: workOrderForm.value.linkOrder,
          label: workOrderForm.value.linkOrderCn
        }
      ]
      formParams.value.businessId = workOrderForm.value.linkOrder
    }
  } else if (businessTitle.value == '商机跟进') {
    isBusinessName.value = true
    isSite.value = true
    taskDescription.value = '任务描述'
    associatedTitle.value = '关联商机:'
  } else if (businessTitle.value == '联系人') {
    isBusinessName.value = true
    isSite.value = true
    taskDescription.value = '任务描述'
    associatedTitle.value = '关联联系人:'
  } else if (businessTitle.value == '采购订单') {
    isBusinessName.value = true
    isSite.value = true
    taskDescription.value = '任务描述'
    associatedTitle.value = '关联采购订单:'
  } else if (businessTitle.value == '内部订单') {
    isBusinessName.value = true
    isSite.value = true
    taskDescription.value = '任务描述'
    associatedTitle.value = '关联内部订单:'
  } else if (businessTitle.value == '项目') {
    isBusinessName.value = true
    isSite.value = true
    associatedTitle.value = '关联项目:'
    taskDescription.value = '任务描述'
    // 工单转任务
    if (workOrderForm.value.linkProject) {
      optionsProjectName.value = [
        {
          value: workOrderForm.value.linkProject,
          label: workOrderForm.value.linkProjectCn
        }
      ]
      formParams.value.businessId = workOrderForm.value.linkProject
    }
  } else if (businessTitle.value == '上门服务') {
    isBusinessType.value = true
    isBusinessName.value = false
    isSite.value = false
    taskDescription.value = '任务描述'
    // 工单转任务
    if (workOrderForm.value.customerId) {
      formParams.value['customerName'] = workOrderForm.value.customerIdCn
      formParams.value['customerId'] = workOrderForm.value.customerId
      formParams.value.contactTel = workOrderForm.value.customerPhone
      formParams.value.cusAddr = workOrderForm.value.customerAddress
    }
  } else if (businessTitle.value == '测试问题') {
    isOperateParentId.value = true
    isBusinessName.value = false
    isSite.value = true
    taskDescription.value = '测试问题描述'
  } else if (businessTitle.value == '功能需求') {
    isOperateParentId.value = true
    isBusinessName.value = false
    isSite.value = false
    taskDescription.value = '功能需求内容'
    if (workOrderForm.value.projectName) {
      formParams.value.businessName = workOrderForm.value.projectName
    }
  } else if (businessTitle.value == '生产BUG') {
    isOperateParentId.value = true
    isBusinessName.value = false
    isSite.value = false
    taskDescription.value = 'BUG描述'
  } else if (businessTitle.value == '数据统计') {
    isOperateParentId.value = true
    isBusinessName.value = false
    isSite.value = false
    taskDescription.value = '统计内容描述'
  } else if (businessTitle.value == '美工设计') {
    isOperateParentId.value = true
    isBusinessName.value = false
    isSite.value = false
    taskDescription.value = '设计内容描述'
  } else {
    isOperateParentId.value = true
    isBusinessName.value = false
    isSite.value = true
    taskDescription.value = '任务描述'
  }
}

// queryString 过滤下拉框
const projectList = ref([])
function queryList() {
  getProjectNodeList().then(res => {
    projectList.value = res.data
  })
}
queryList()
const querySearch = (queryString, cb) => {
  const results = queryString
    ? projectList.value.filter(createFilter(queryString, 'businessName'))
    : projectList.value
  // call callback function to return suggestions
  const data = results.map(v => {
    return {
      value: v.businessName,
      label: v.businessId
    }
  })
  cb(data)
}
// 父任务
const timer = ref()
const taskList = ref([])
const options = ref([])
function remoteMethod(query) {
  if (!formParams.value.businessId && showProjectName.value) {
    return false
  }
  const params = {
    keyword: query || '',
    pageSize: 10,
    pageNum: 1
  }
  if (showProjectName.value) {
    params.businessId = formParams.value.businessId
  } else {
    params.businessType = formParams.value.businessType
  }
  // if (query) {
  timer.value = setTimeout(() => {
    getTaskList(params).then(res => {
      taskList.value = res.rows || []
      options.value = taskList.value.filter(item => {
        return item.title.toLowerCase().includes(query.toLowerCase())
      })
    })
  }, 300)
  // } else {
  //   options.value = []
  // }
}

function parentInputfocus() {
  if (!formParams.value.businessId && showProjectName.value) {
    options.value = []
    proxy.$modal.msgWarning('请先选择系统/项目名称')
    const timer = setTimeout(() => {
      proxy.$refs.parentInput.blur()
      clearTimeout(timer)
    }, 300)
    return
  }
}

const createFilter = (queryString, key = 'label') => {
  return restaurant => {
    return restaurant[key].indexOf(queryString) !== -1
  }
}

// 表单赋值businessName
function valueChange(val) {
  console.log(val)
  if (val) {
    const data = projectList.value.find(v => v.businessName === val.value)
    formParams.value.businessName = val.value
    formParams.value.businessId = val.label
  } else {
    formParams.value.businessId = ''
    name.value = ''
  }

  console.log(formParams.value.businessId)
}
function blurValue() {
  if (!projectList.value.length) {
    name.value = ''
  }
}
// 父任务赋值
function handleSelect(val) {
  const data = taskList.value.find(v => v.title === val.value)
  formParams.value.parentId = val.label
  // formParams.value.parentIdCn = val.value
}

// 数组转换树
/**
 * @params arr 输入数组
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}

/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = formParams.value.customerType
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      dialogParamA.value.defaultCheckedKeys = formParams.value[keyName]
      dialogParamA.value.defaultCheckedLabel = formParams.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
  }
}

// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      formParams.value.customerType = val.tabVal
      formParams.value.customerName = val.labelData.toString()
      formParams.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      if (formParams.value.customerId) {
        selectCustomerItem()
      }
      break
  }
}
async function selectCustomerItem() {
  switch (formParams.value.customerType) {
    case 'customer':
      changeCustomer(formParams.value.customerId)
      break
    case 'cusLink':
      formParams.value.contactId = formParams.value.customerId
      formParams.value.contactName = formParams.value.customerName
      await queryContacts(formParams.value.contactName)
      await contactsChange(formParams.value.contactId)
      break
  }
}
/***客户联系人数据  start*/
const contactsOptions = ref([])
//联系人
async function queryContacts(val) {
  let params = {
    pageSize: 10,
    entId: '',
    contactName: val || ''
  }
  let res = await getDetailTactlistByCactName(params)
  contactsOptions.value = res.data
}
// 改变客户名称后客户联系人 联系电话清空
async function changeCustomer(val) {
  // //获取客户联系人
  await getCustomerEditInfo(val).then(res => {
    let resData = res.data
    //联系人赋值
    if (resData.bizCustomerAddDto.mainContactId) {
      formParams.value.contactId = resData.bizCustomerAddDto.mainContactId
      formParams.value.contactName = resData.bizCustomerAddDto.mainContactName
    }
    //联系电话赋值
    if (resData.bizCustomerAddDto.mainContactPhone) {
      var contactPhone = resData.bizCustomerAddDto.mainContactPhone
    }
    formParams.value.contactTel = formParams.value.contactName + contactPhone
  })
}
// 客户联系人选中事件
const contactsChange = val => {
  formParams.value.contactTel = ''
  let newData = JSON.parse(JSON.stringify(contactsOptions.value))
  let obj = newData.filter(item => {
    return item.id == val
  })
  formParams.value.contactTel = obj[0].contactName + obj[0].contactNumber
}
function radioClick(item) {}
//获取当前时间
function getTime() {
  var _this = this
  let yy = new Date().getFullYear()
  var mm =
    new Date().getMonth() > 9
      ? new Date().getMonth() + 1
      : new Date().getMonth() == 9
      ? new Date().getMonth() + 1
      : '0' + (new Date().getMonth() + 1)
  var dd =
    new Date().getDate() < 10
      ? '0' + new Date().getDate()
      : new Date().getDate()
  let hh = new Date().getHours()
  let mf =
    new Date().getMinutes() < 10
      ? '0' + new Date().getMinutes()
      : new Date().getMinutes()
  let ss =
    new Date().getSeconds() < 10
      ? '0' + new Date().getSeconds()
      : new Date().getSeconds()
  gettime.value = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
}
//
function handleSave() {}
//保存
async function handleSubmit() {
  proxy.$refs['ruleFormRef'].validate(valid => {
    if (valid) {
      if (formParams.value.id) {
        formParams.value.playersId = playersId
        let data = JSON.parse(JSON.stringify(formParams.value))
        data.directorId = data.directorId.replace('U', '')
        if (isArray(data.fileList)) {
          delete data.fileList
        }

        // 通知人员
        if (Array.isArray(data.copyId)) {
          for (let i = 0; i < data.copyId.length; i++) {
            data.copyId[i] = data.copyId[i].replace('U', '')
          }
          data.copyId = data.copyId.toString()
        }

        data.fileName = []
        data.filePath = []
        if (fileList.value.length > 0) {
          for (let i = 0; i < fileList.value.length; i++) {
            data.fileName.push(fileList.value[i].origFileName)
            data.filePath.push(fileList.value[i].url)
          }
        }
        data.fileName = data.fileName ? data.fileName.toString() : ''
        data.filePath = data.filePath ? data.filePath.toString() : ''
        // 更新通知人员
        updateTadk(data).then(res => {
          if (res.code === 200) {
            btnLoading.value = false
            proxy.$modal.msgSuccess('修改成功!')
            if (updateData.value?.length) {
              const len = updateData.value.length
              for (let i = 0; i < len; i++) {
                // 通知人员
                let mesData = {
                  businessId: '任务-通知-' + updateData.value[i].id, //业务ID
                  content: `${userStore.user.nickName}创建了一条任务:${data.title}`,
                  followDate: undefined, //跟进日期
                  followType: undefined, //跟进方式
                  impSign: '2', //
                  receiver: updateData.value[i].id, //接收人id
                  receiverName: updateData.value[i].label, //接收人中文
                  reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
                  sendTime: gettime.value, //发送时间
                  sender: userStore.user.nickName, //发送人
                  title: '您有一条任务通知待浏览', //待办标题
                  type: 0, //待办类型:0-普通，1-流程
                  serviceType: '10', //服务类型 1-准时提醒
                  urgFlag: data.impSign, //紧急程度:0-非常紧急，1-紧急，2-一般
                  urlName: '前往查看', //待办链接名称(多链接名称用英文逗号隔开)
                  url: `/rsgl/other/taskDetails?id=${route.query.id}` //待办链接(多链接用英文逗号隔开)
                }
                addManage(mesData).then(res => {})
              }
            }
            router.push({
              path: '/rsgl/other/taskManage'
            })
            useTagsViewStore().delView(router.currentRoute.value)
          } else {
            btnLoading.value = false
          }
        })
      } else {
        //   data.playersId = []
        formParams.value.fqr = userStore.user.nickName
        formParams.value.fqdw = userStore.user.params.orgName
        let data = JSON.parse(JSON.stringify(formParams.value))
        data.fileName = []
        data.filePath = []
        delete data.fileList
        data.businessType = data.businessType.toString()
        if (formParams.value.directorId) {
          // 获取查询到的user数据对象
          let userObj = getUniqueUserId(
            selectOptionObj.value['directorId'],
            formParams.value.directorId
          )
          //获取userid
          data.directorId = userObj.id
        }
        //参与人员
        if (data.playersId) {
          for (let i = 0; i < data.playersId.length; i++) {
            data.playersId[i] = data.playersId[i].replace('U', '')
          }
        }
        // 通知人员
        if (Array.isArray(data.copyId)) {
          for (let i = 0; i < data.copyId.length; i++) {
            data.copyId[i] = data.copyId[i].replace('U', '')
          }
        }

        data.copyId = data.copyId ? data.copyId.toString() : ''
        data.playersId = data.playersId ? data.playersId.toString() : ''
        //   data.reminderMethod = data.reminderMethod ? data.reminderMethod.toString() : ''

        if (fileList.value.length > 0) {
          for (let i = 0; i < fileList.value.length; i++) {
            data.fileName.push(fileList.value[i].origFileName)
            data.filePath.push(fileList.value[i].url)
          }
        }
        data.fileName = data.fileName ? data.fileName.toString() : ''
        data.filePath = data.filePath ? data.filePath.toString() : ''
        btnLoading.value = true
        // 工单转任务
        if (route.query.workOrderTransform && workOrderForm.value.workOrderId) {
          data.workId = workOrderForm.value.workOrderId
        }
        addTaskList(data)
          .then(res => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess('添加成功!')
              let taskId = ''
              for (let i = 0; i < res.data.length; i++) {
                // 参与人员通知
                let mesVoData = {
                  businessId: '任务-通知-' + res.data[i].operateId, //业务ID
                  content: `${data.title}:${data.remark ? data.remark : ''}`,
                  followDate: undefined, //跟进日期
                  followType: undefined, //跟进方式
                  impSign: '1', //
                  receiver: res.data[i].belongId, //接收人id
                  receiverName: res.data[i].belongName, //接收人中文
                  reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
                  sendTime: gettime.value, //发送时间
                  sender: userStore.user.nickName, //发送人
                  title: `您有一条'${data.title}'任务待处理`, //待办标题
                  type: 0, //待办类型:0-普通，1-流程
                  serviceType: '10', //服务类型 1-准时提醒
                  urgFlag: data.impSign, //紧急程度:0-非常紧急，1-紧急，2-一般
                  urlName: '前往处理', //待办链接名称(多链接名称用英文逗号隔开)
                  url: `/rsgl/other/taskProcessing?id=${res.data[i].taskId}&operateId=${res.data[i].operateId}` //待办链接(多链接用英文逗号隔开)
                }
                if (!taskId) {
                  taskId = res.data[i].taskId
                }
                // mesVoData.content = mesVoData.content.replace(
                //   /<\/?[a-zA-z]*>/g,
                //   '\n\r'
                // )
                addManage(mesVoData).then(res => {})
              }
              if (data.copyId) {
                const arr = data.copyId.split(',')
                const copyName = data.copyName.split(',')
                const len = arr.length
                for (let i = 0; i < len; i++) {
                  // 通知人员
                  let mesData = {
                    businessId: '任务-通知-' + arr[i], //业务ID
                    content: `${userStore.user.nickName}创建了一条任务:${data.title}`,
                    followDate: undefined, //跟进日期
                    followType: undefined, //跟进方式
                    impSign: '2', //
                    receiver: arr[i], //接收人id
                    receiverName: copyName[i], //接收人中文
                    reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
                    sendTime: gettime.value, //发送时间
                    sender: userStore.user.nickName, //发送人
                    title: '您有一条任务通知待浏览', //待办标题
                    type: 0, //待办类型:0-普通，1-流程
                    serviceType: '10', //服务类型 1-准时提醒
                    urgFlag: data.impSign, //紧急程度:0-非常紧急，1-紧急，2-一般
                    urlName: '前往查看', //待办链接名称(多链接名称用英文逗号隔开)
                    url: `/rsgl/other/taskDetails?id=${taskId}` //待办链接(多链接用英文逗号隔开)
                  }
                  addManage(mesData).then(res => {})
                }
              }

              btnLoading.value = false
              useTagsViewStore().delView(router.currentRoute.value)
              router.go(-1)
            } else {
              btnLoading.value = false
            }
          })
          .catch(err => {
            btnLoading.value = false
          })
      }
    }
  })
}
// 选择任务类型

/**
 * 弹出框关闭
 * @param {*} val
 */
const closeFn = val => {
  dialogParam.value.isDialog = false
}

// 通知人员弹出
function noticeFocus() {
  const user = useUserStore().user['orgId']
  dialogParam.value = {
    type: 'copyId',
    title: '请选择通知人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false
    // defaultCheckedKeys:[100]
  }
  dialogParam.value.isDialog = true
  dialogParam.value.apiParams = {
    disabled: 'false',
    deptId: user == '484' ? '100' : user
    // deptId:'484'
  }
  if (formParams.value.copyId) {
    dialogParam.value.defaultCheckedKeys =
      typeof formParams.value.copyId === 'string'
        ? [formParams.value.copyId]
        : formParams.value.copyId
  } else {
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 参与人获取焦点事件
 */
function participateIdFocus() {
  const user = useUserStore().user['orgId']
  dialogParam.value = {
    type: 'playersId',
    title: '请选择参与人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false
    // defaultCheckedKeys:[100]
  }
  dialogParam.value.isDialog = true
  dialogParam.value.apiParams = {
    disabled: 'false',
    deptId: user == '484' ? '100' : user
    // deptId:'484'
  }
  if (formParams.value.playersId) {
    dialogParam.value.defaultCheckedKeys =
      typeof formParams.value.playersId === 'string'
        ? [formParams.value.playersId]
        : formParams.value.playersId
  } else {
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 负责人获取焦点事件
 */
function userInputFocus() {
  const user = useUserStore().user['orgId']
  dialogParam.value = {
    type: 'directorId',
    title: '请选择负责人员',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: false,
    checkStrictly: false
  }
  dialogParam.value.isDialog = true
  dialogParam.value.apiParams = {
    // disabled: 'false',
    deptId: user == '484' ? '100' : user
    // deptId:'484'
  }

  dialogParam.value.defaultCheckedKeys = [formParams.value.directorId] || []
}
/** 弹出框下拉框
 * 负责人
 * @param {*} val  selectDialog组件返回的值
 */

const updateData = ref()
const selectDialogData = val => {
  switch (val.type) {
    case 'directorId':
      selectOptionObj.value['directorId'] = val.selectData
      formParams.value.director = val.labelData.toString()
      formParams.value.directorId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : ''
      break
    case 'playersId':
      selectOptionObj.value['playersId'] = val.selectData
      formParams.value.players = val.labelData.toString()
      formParams.value.playersId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : ''

      break
    case 'copyId':
      // 编辑时更改通知人员，获取变更人员
      if (route.query.id) {
        updateData.value = val.selectData.filter(v => {
          if (
            !selectOptionObj.value['copyId'].find(item => item.uuid == v.id)
          ) {
            return v
          }
        })
      }
      selectOptionObj.value['copyId'] = val.selectData
      formParams.value.copyName = val.labelData.toString()
      formParams.value.copyId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : ''

      break
  }
}

/**文件上传 限制条件**/
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    // proxy.$modal.msgError(error)
  }
}
//删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    // proxy.$modal.msgError(error)
  }
}

//返回
function handleBack() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}

// 期望时间设置格式
function timeChange(val) {
  if (val) {
    formParams.value.endTime = val.replace('00:00:00', '23:59:59')
  }
}

const showUpload = ref(false)
// 批量导入功能
function importList() {
  showUpload.value = true
}

function uploadFiles() {
  // proxy.$refs['uploadRef'].submit()
  if (uploadfile.value) {
    let formData = new FormData()
    formData.append('file', uploadfile.value)
    importTask(formData)
      .then(res => {
        proxy.$modal.msgSuccess('导入成功')
        showUpload.value = false
        useTagsViewStore().delView(router.currentRoute.value)
        router.push('/rsgl/other/taskManage')
        if (res.data?.length) {
          let mesData = {
            businessId: '任务-通知-' + new Date(), //业务ID
            content: '您有一批新任务',
            followDate: undefined, //跟进日期
            followType: undefined, //跟进方式
            impSign: '2', //
            receiver: res.data.map(v => v.belongId).toString(), //接收人id
            receiverName: res.data.map(v => v.belongName).toString(), //接收人中文
            reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
            sendTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'), //发送时间
            sender: userStore.user.nickName, //发送人
            title: '您有一条任务通知待浏览', //待办标题
            type: 0, //待办类型:0-普通，1-流程
            serviceType: '10', //服务类型 1-准时提醒
            urgFlag: data.impSign, //紧急程度:0-非常紧急，1-紧急，2-一般
            urlName: '前往查看', //待办链接名称(多链接名称用英文逗号隔开)
            url: '/rsgl/other/taskManage' //待办链接(多链接用英文逗号隔开)
          }
          addManage(mesData).then(res => {})
        }
      })
      .catch(() => {
        proxy.$refs['uploadRef'].clearFiles()
      })
  }
}

function cancelupload() {
  showUpload.value = false
}
// 下载模板
function downloadTemplate() {
  proxy.downLoadByUrl('/system/task/importtemplate', {}, '任务导入模板.xlsx')
}

function closeUpload() {
  showUpload.value = false
}

const uploadfile = ref()
function fileChange(file, files) {
  console.log(file, files)
  if (!file) {
    return
  }
  const index = file.raw.name.lastIndexOf('.')
  const fileType = file.raw.name.slice(index + 1)
  if (fileType != 'xlsx' && fileType != 'xls') {
    proxy.$modal.msgError('请上传xlsx或xls格式的文件')
    return
  }
  uploadfile.value = file.raw
}
</script>

<style lang="scss" scoped>
.addTask-page {
  display: block;

  .addTask-com {
    padding: 24px;
  }

  .my-header {
    display: flex;
    height: 36px;

    .flex-header-7 {
      flex: 7;
      font-size: 18px;
      font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
      font-weight: bold;
      margin-top: 8px;
    }

    .flex-header-5 {
      flex: 5;
      margin-top: 2px;
      min-width: 500px;
      text-align: right;
    }
  }

  .el-button--small.is-round {
    padding: 15px 11px;
  }

  .dispose-title {
    font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
  }

  .jx-color {
    color: #f59a23;
  }

  .wc-color {
    color: #4bd863;
  }

  .circleUrl-box {
    display: inline-block;

    .circleUrl-img {
      float: left;
      margin: 0 6px;
      //   width: 90px;
      text-align: center;
    }
  }

  .border-bottom-title {
    margin: 16px 0 0 0;
    width: 100%;
    height: 36px;
    line-height: 36px;
    font-size: 15px;
    background: white;
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #666;
    font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
  }

  .border-bottom-title span {
    float: left;
    padding: 10px 0 0 10px;
  }

  .border-bottom-title div {
    float: left;
    padding-left: 3px;
  }

  .annex-box {
    padding: 0px 10px 10px 10px;

    .annex-flex {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      border: 1px solid #eee;
      padding: 12px 18px;
      line-height: 40px;
      margin-top: 18px;

      .annex-flex-6 {
        flex: 11;
        font-size: 14px;
      }

      .annex-flex-1 {
        // flex: 1;
        display: inline-block;
        width: 30px;
      }

      .annex-flex-12 {
        flex: 15;
        font-size: 14px;
      }

      .annex-flex-4 {
        flex: 4;
      }

      .annex-flex-3 {
        flex: 3;
      }

      .annex-flex-2 {
        flex: 2;
      }

      .annex-title {
        color: #409efc;
      }
    }
  }
  // 阻止点击label 选择input
  ::v-deep(.el-form-item__label) {
    pointer-events: none;
  }
  .uploadStyle {
    width: 100%;
    height: 90px;
    border: 1px dotted #ccc;
  }
}
</style>
